package agency.web.app.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import agency.web.app.domain.Agent;
import agency.web.app.domain.Client;
import agency.web.app.domain.User;
import agency.web.app.repository.UserDao;
import agency.web.app.service.ClientService;

@Service
@Transactional
public class ClientServiceImpl extends UserServiceImpl implements ClientService {

	@Autowired
	private UserDao clientRepository;

	public Client clientRegistration(String login, String password) {
		return (Client) clientRepository.userRegistration(login, password);

	}

	public void addClient(Client c) {
		clientRepository.add(c);

	}

	public void modifyClient(Client c) {
		clientRepository.modify(c);

	}

	public List<Client> findAllClients() {
		List<User> users = clientRepository.findAll();
		List<Client> list = new ArrayList<Client>();
		for (User u : users) {
			if (isClient(u))
				list.add((Client) u);
		}
		return list;
	}

	public Client findClientById(int id) {
		return (Client) clientRepository.findById(id);
	}

	public List<Client> findClientByName(String name) {
		Criterion criterion = Restrictions.eq("NAME", name);
		List<User> users = clientRepository.findByCriteria(criterion);
		List<Client> list = new ArrayList<Client>();
		for (User u : users) {

			if (isClient(u))
				list.add((Client) u);
		}
		return list;
	}

	public List<Client> findClientByAgent(Agent agent) {
		Criterion criterion = Restrictions.eq("AGENT", agent.getUserId());
		List<User> users = clientRepository.findByCriteria(criterion);
		List<Client> list = new ArrayList<Client>();
		for (User u : users) {
			if (isClient(u))
				list.add((Client) u);
		}
		return list;
	}

	public void calculateDiscount() {
		
		List<User> users = clientRepository.findAll();
		List<Client> list = new ArrayList<Client>();	
		int nb = 0;
		
		for (User u:users){
			for (int i = 0; i < users.size()-1; i++) {
				for (int j = i+1; j < users.size()-1; j++) {
					if (users.get(i).getUserId()== users.get(j).getUserId()) { 
						nb++;
						}
			}
			}
			
			double newDiscount = ((Client) u).getDiscount() + nb*2.5;
			((Client) u).setDiscount(newDiscount);
			
			if (isClient(u)){
				list.add((Client) u);
			}
		}
	
	}

	public void deleteClientById(int id) {
		clientRepository.delete(id);

	}

	public void deleteClient(Client c) {
		clientRepository.delete(c);

	}

	public void logoutClient(int clientId) {
		// TODO Auto-generated method stub
		
	}

}
